import Vue from 'vue'
import Axios from 'axios'
import Qs from 'qs'
import { Message } from 'element-ui'

const ContentTypeConstant = {
  // application/json; charset=utf-8 已 json 格式发送数据，data 传 javascript 对象时的默认值
  CONTENT_TYPE_JSON: 'application/json; charset=utf-8',
  // application/x-www-form-urlencoded; charset=utf-8 以传统表单的格式发送数据，数据被自动 qs 格式化，处理成键值对
  CONTENT_TYPE_URL_ENCODE: 'application/x-www-form-urlencoded; charset=utf-8',
  // multipart/form-data 格式 用于发送文件，data 内的内容自动被处理成 FormData
  CONTENT_TYPE_FORM_DATA: 'multipart/form-data'
}
const VUE_APP_SERVER_URL = process.env.VUE_APP_SERVER_URL
const instance = Axios.create({
  baseURL: VUE_APP_SERVER_URL,
  // 系统post请求默认使用application/json，其他请求方式请自定义或使用下方的快捷方法
  headers: { post: { 'Content-Type': ContentTypeConstant.CONTENT_TYPE_JSON } },
  // 系统get请求，默认使用QS格式化请求参数
  paramsSerializer: {
    serialize (params) {
      const fq = Qs.stringify(params, {
        allowDots: true,
        arrayFormat: 'indices'
      })
      return fq
    }
  }
})

// 配置POST请求默认ContentType为application/json
// instance.defaults.headers.post['Content-Type'] = ContentTypeConstant.CONTENT_TYPE_JSON

instance.interceptors.request.use(request => {
  return request
})

instance.interceptors.response.use(response => {
  return Promise.resolve(response)
}, error => {
  console.log('error', error)
  if (error.response.status === 500 || error.response.status === 501) {
    if (error.response.data.message) {
      Message.error(error.response.data.message)
    } else {
      Message.error('服务器错误')
    }
  } else {
    Message.error('请求失败')
  }
  return Promise.reject(error)
})

//
instance.postUrlEncode = (url, data, config) => {
  return instance.request({
    // ...(config || {}),
    ...config,
    url,
    method: 'post',
    headers: {
      ...(config || {}).headers,
      'Content-Type': ContentTypeConstant.CONTENT_TYPE_URL_ENCODE
    },
    data: Qs.stringify(data, {
      allowDots: true,
      arrayFormat: (config && config.arrayFormat) || 'indices'
    })
  })
}

instance.postJson = (url, data, config) => {
  return instance.request({
    // ...(config || {}),
    ...config,
    url,
    data,
    method: 'post',
    headers: {
      ...(config || {}).headers,
      'Content-Type': ContentTypeConstant.CONTENT_TYPE_JSON
    }
  })
}

instance.postFormData = (url, data, config) => {
  return instance.request({
    ...config,
    url,
    data,
    method: 'post',
    headers: {
      ...(config || {}).headers,
      'Content-Type': ContentTypeConstant.CONTENT_TYPE_FORM_DATA
    }
  })
}

instance.download = (url, params, config) => {
  return instance.request({
    url,
    params,
    ...config,
    responseType: 'blob'
  }).then((resp) => {
    const blob = new Blob([resp.data], { type: resp.headers['content-type'] })
    const url = window.URL.createObjectURL(blob)
    const aEl = window.document.createElement('a')
    aEl.target = '_blank'
    aEl.href = url
    aEl.style.display = 'none'
    aEl.download = /filename=([^;\\.]+\.[^;\\.]+);*/.exec(resp.headers['content-disposition'])[1]
    aEl.click()
    window.URL.revokeObjectURL(url)
    return Promise.resolve(resp.data)
  })
}

/* request.interceptors.request.use(config => {
  !!config.contentType && (config.headers['Content-Type'] = config.contentType)
  if (config.method.toLowerCase() === 'post' && config.headers['Content-Type'] === ContentTypeConstant.CONTENT_TYPE_FORM) {
    config.data = Qs.stringify(config.data)
  }
  console.log(config)
  return config
}, error => {
  return Promise.reject(error)
}) */

Vue.prototype.$axios = Axios
Vue.prototype.$http = instance

export default instance
